package edu.ycu.aladdin.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Set;

/**
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
public class GenerateUtils {

    /**
     * 将json转换为java文本.
     * 例子:
     * {@code
     * String input = "{'logId':'001','index':001,'logType':'INFO','other':null}";
     * String outPut = generateJavaTextFromJson(input,"private");
     * // 结果:
     * // private String logType;
     * // private Object other;
     * // private Integer index;
     * // private String logId;
     * }
     * @param json 输入json字符串
     * @param prefix 前缀(如访问修饰符)
     * @return 生成的JAVA文本
     */
    public static String generateJavaTextFromJson(String json, String prefix){

        StringBuilder stringBuilder = new StringBuilder();

        JSONObject jsonObject = JSON.parseObject(json);
        Set<String> keySet = jsonObject.keySet();
        keySet.stream().forEach(key->{
            Object value = jsonObject.get(key);
            stringBuilder.append(prefix+" "+getJavaTypeString(value)+" "+key+";\n");
        });
        return stringBuilder.toString();
    }

    /**
     * 获取类型字符
     * eg:
     *   getJavaTypeString("string")->String
     *   getJavaTypeString(123)->Integer
     * @param object
     * @return
     */
    public static String getJavaTypeString(Object object){
        if (object!=null){
            return object.getClass().getCanonicalName().replace("java.lang.","");
        }
        return "Object";
    }
}
